namespace NHCodeFirst.FluentMapper
{
    using System;
    using System.Linq.Expressions;
    using Enums;
    using HbmModel;
    using Helpers;

    public class KeyMapper<TEntity>
    {
        private readonly Key key;

        internal KeyMapper(Key key)
        {
            this.key = key;
        }

        public KeyMapper<TEntity> ForeignKey(string value)
        {
            key.ForeignKey = value;
            return this;
        }

        public KeyMapper<TEntity> OnDelete(KeyOnDelete onDelete)
        {
            switch (onDelete)
            {
                case KeyOnDelete.Cascade:
                    key.OnDelete = "cascade";
                    break;
                case KeyOnDelete.NoAction:
                    key.OnDelete = "no-action";
                    break;
            }
            return this;
        }

        public KeyMapper<TEntity> Update(bool value)
        {
            key.Update = value.ToString().ToLower();
            return this;
        }

        public KeyMapper<TEntity> AddKey(string name, Action<ColumnMapper> mapper = null)
        {
            var column = new Column {Name = name};
            if (mapper != null)
                mapper(new ColumnMapper(column));
            key.Columns.Add(column);
            return this;
        }

        public KeyMapper<TEntity> AddKey<TProperty>(Expression<Func<TEntity,TProperty>> selector, Action<ColumnMapper> mapper = null)
        {
            return AddKey(new ExpressionHelper().GetPropertyName(selector), mapper);
        }
    }

    public class KeyMapper
    {
        private readonly Key key;

        internal KeyMapper(Key key)
        {
            this.key = key;
        }

        public KeyMapper ForeignKey(string value)
        {
            key.ForeignKey = value;
            return this;
        }

        public KeyMapper OnDelete(KeyOnDelete onDelete)
        {
            switch (onDelete)
            {
                case KeyOnDelete.Cascade:
                    key.OnDelete = "cascade";
                    break;
                case KeyOnDelete.NoAction:
                    key.OnDelete = "no-action";
                    break;
            }
            return this;
        }

        public KeyMapper Update(bool value)
        {
            key.Update = value.ToString().ToLower();
            return this;
        }

        public KeyMapper AddKey(string name, Action<ColumnMapper> mapper = null)
        {
            var column = new Column { Name = name };
            if (mapper != null)
                mapper(new ColumnMapper(column));
            key.Columns.Add(column);
            return this;
        }
    }
}